package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.wanglu1209.bannerlibrary.Banner;
import com.github.wanglu1209.bannerlibrary.BannerPagerAdapter;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Model.Request.HomePageBannerReq;
import com.ydkj.a37e_mall.Classes.Model.Request.leftTpyeReq;
import com.ydkj.a37e_mall.Classes.Model.Response.BannerInfoResp;
import com.ydkj.a37e_mall.Classes.Model.Response.RightDataTpyeResp;
import com.ydkj.a37e_mall.Classes.Model.Response.leftTpyeResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.MyGridView;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/2/9.
 * 侧滑分类
 */

public class SortSlidingActivity extends BaseActivity implements View.OnClickListener {
    private Activity mActivity;

    private RelativeLayout back;
    private LinearLayout lly_sliding_search;
    private TextView tv_sliding_adress;
    private ListView lv_sort_left;
    private ListView lv_sort_right;
    private Banner banner;
    private LeftsortAdapter leftsortAdapter;
    private RightsortAdapter rightsortAdapter;
    private RightgridAdapter rightadapter;
    private List<leftTpyeResp.ResultEntity.DataEntity> lefttpyedatalist;
    private List<RightDataTpyeResp.ResultEntity.DataEntity> rightdatatypelist;
    private List<BannerInfoResp.ResultEntity.DataEntity> bannerList;
    private int code = 0;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sort_sliding);
        mActivity = this;
//        initWindow();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);

        LoadBanner();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {

        back = (RelativeLayout) mActivity.findViewById(R.id.rly_classification);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        lly_sliding_search = (LinearLayout) mActivity.findViewById(R.id.lly_sliding_search);
        tv_sliding_adress = (TextView) mActivity.findViewById(R.id.tv_adress);

        //左边列表数据
        lefttpyedatalist = new ArrayList<>();
        lv_sort_left = (ListView) mActivity.findViewById(R.id.lv_sort_left);
        leftsortAdapter = new LeftsortAdapter(lefttpyedatalist);
        lv_sort_left.setAdapter(leftsortAdapter);


        //右边列表数据
        rightdatatypelist = new ArrayList<>();
        lv_sort_right = (ListView) mActivity.findViewById(R.id.lv_sort_right);
        rightsortAdapter = new RightsortAdapter(rightdatatypelist);
        lv_sort_right.setAdapter(rightsortAdapter);


        lly_sliding_search.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lly_sliding_search:
                startActivity(new Intent(mActivity, Search.class));
                break;
        }
    }


    //获取左边列表的数据
    private void GetleftTpye() {
        CustomProgressDialog.createDialog(mActivity).show();
        leftTpyeReq req = new leftTpyeReq();
        req.setType("1");
        req.setGet_sub("0");
        req.setPage("1");
        req.setPage_size("100");

        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    leftTpyeResp resp = GsonImpl.get().toObject(response.toString(), leftTpyeResp.class);
                    lefttpyedatalist.addAll(resp.getResult().getData());
                    leftsortAdapter.notifyDataSetChanged();
                    GetrightDataTpye(lefttpyedatalist.get(0).getId());
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接异常");
            }
        });

    }

    //左边的adapter
    private class LeftsortAdapter extends BaseAdapter {
        private List<leftTpyeResp.ResultEntity.DataEntity> lefttpyedatalist;

        private LeftsortAdapter(List<leftTpyeResp.ResultEntity.DataEntity> info) {
            if (info == null) {
                info = new ArrayList<>();
            }
            lefttpyedatalist = info;
        }

        @Override
        public int getCount() {
            return lefttpyedatalist.size();
        }

        @Override
        public leftTpyeResp.ResultEntity.DataEntity getItem(int position) {
            return lefttpyedatalist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.leftsottsliding_list, null);
                vh = new ViewHolder();
                vh.tv_leftsort = (TextView) convertView.findViewById(R.id.tv_leftsort);
                vh.lly_leftsort = (LinearLayout) convertView.findViewById(R.id.lly_leftsort);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);

            if (code == 0) {
                if (position == 0) {
                    leftTpyeResp.ResultEntity.DataEntity info = lefttpyedatalist.get(position);
                    info.setIs_check(true);
                    code++;
                }
            }

            vh.tv_leftsort.setText(lefttpyedatalist.get(position).getName());
            vh.lly_leftsort.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("ssss", "ididi==>" + lefttpyedatalist.get(position).getId());
                    leftTpyeResp.ResultEntity.DataEntity info = lefttpyedatalist.get(position);
                    for (leftTpyeResp.ResultEntity.DataEntity infos : lefttpyedatalist) {
                        if (infos.getName().equals(info.getName())) {
                            infos.setIs_check(true);
                        } else {
                            infos.setIs_check(false);
                        }
                    }
                    leftsortAdapter.notifyDataSetChanged();
                    GetrightDataTpye(lefttpyedatalist.get(position).getId());
                }
            });

            leftTpyeResp.ResultEntity.DataEntity info = lefttpyedatalist.get(position);
            if (info.is_check()) {
                vh.tv_leftsort.setTextColor(getResources().getColor(R.color.Af2061b));
            } else {
                vh.tv_leftsort.setTextColor(getResources().getColor(R.color.A333333));
            }

            return convertView;
        }

        private class ViewHolder {
            private LinearLayout lly_leftsort;
            TextView tv_leftsort;
        }
    }

    //获取右边数据的数据
    private void GetrightDataTpye(String type) {
        CustomProgressDialog.createDialog(mActivity).show();
        leftTpyeReq req = new leftTpyeReq();
        req.setType(type);
        req.setGet_sub("1");
        req.setPage("1");
        req.setPage_size("100");

        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());
//        Log.e("ssss", "secret==>" + secret);
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("ssss", "response==>" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    RightDataTpyeResp resp = GsonImpl.get().toObject(response.toString(), RightDataTpyeResp.class);
                    rightdatatypelist.clear();
                    rightdatatypelist.addAll(resp.getResult().getData());

                    rightsortAdapter.notifyDataSetChanged();

                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接异常");
            }
        });

    }

    //右边的标题的adapter
    private class RightsortAdapter extends BaseAdapter {
        private List<RightDataTpyeResp.ResultEntity.DataEntity> rightdatatypelist;

        private RightsortAdapter(List<RightDataTpyeResp.ResultEntity.DataEntity> info) {
            if (info == null) {
                info = new ArrayList<>();
            }
            rightdatatypelist = info;
        }

        @Override
        public int getCount() {
            return rightdatatypelist.size();
        }

        @Override
        public RightDataTpyeResp.ResultEntity.DataEntity getItem(int position) {
            return rightdatatypelist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.rightsottsliding_list, null);
                vh = new ViewHolder();
                vh.gv_rightt_sort = (MyGridView) convertView.findViewById(R.id.gv_rightt_sort);
                vh.tv_right_sort = (TextView) convertView.findViewById(R.id.tv_right_name);
                vh.rly_right = (RelativeLayout) convertView.findViewById(R.id.rly_right);


            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            vh.tv_right_sort.setText(rightdatatypelist.get(position).getName());
            vh.rly_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("ssss", "右边数据名称==》" + rightdatatypelist.get(position).getName());
                }
            });

            //listview嵌套下的Gridview
            rightadapter = new RightgridAdapter(rightdatatypelist.get(position).getSub());
            vh.gv_rightt_sort.setAdapter(rightadapter);

            return convertView;
        }

        private class ViewHolder {
            private MyGridView gv_rightt_sort;
            private TextView tv_right_sort;
            private RelativeLayout rly_right;
        }
    }


    //右边的数据的adapter
    private class RightgridAdapter extends BaseAdapter {
        private List<RightDataTpyeResp.ResultEntity.DataEntity.SubEntity> rightdatatypesublist;

        private RightgridAdapter(List<RightDataTpyeResp.ResultEntity.DataEntity.SubEntity> info) {
            if (info == null) {
                info = new ArrayList<>();
            }
            rightdatatypesublist = info;
        }

        @Override
        public int getCount() {
            return rightdatatypesublist.size();
        }

        @Override
        public RightDataTpyeResp.ResultEntity.DataEntity.SubEntity getItem(int position) {
            return rightdatatypesublist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.gvsottsliding_list, null);
                vh = new ViewHolder();
                vh.tv_right_name = (TextView) convertView.findViewById(R.id.tv_right_name);
                vh.lly_right_title = (LinearLayout) convertView.findViewById(R.id.lly_right_title);
                vh.img_right_photo = (ImageView) convertView.findViewById(R.id.img_right_photo);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);

            ImageLoader.getInstance().displayImage(getItem(position).getThumb(), vh.img_right_photo, displayImageOptions);
            vh.tv_right_name.setText(rightdatatypesublist.get(position).getName());

            vh.lly_right_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(mActivity, ProductAcrivity.class);
                    intent.putExtra("id", getItem(position).getId());
                    intent.putExtra("titlename", getItem(position).getName());
                    Log.e("ssss", "商品ID==》" + getItem(position).getId());
                    Log.e("ssss", "商品名称==》" + rightdatatypesublist.get(position).getName());
                    startActivity(intent);
                }
            });
            return convertView;
        }

        private class ViewHolder {
            private LinearLayout lly_right_title;
            private ImageView img_right_photo;
            private TextView tv_right_name;
        }
    }

    //获取banner广告栏（viewpager）
    private void LoadBanner() {
        bannerList = new ArrayList<>();

        HomePageBannerReq req = new HomePageBannerReq();
        req.setType("2");
        req.setPage("1");
        req.setPage_size("6");


        if (sharedPreferencesUtil.getAccessToken() != null) {
            params.put("token", sharedPreferencesUtil.getAccessToken());
        }
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);

                Log.e("url", "viewpager_ad_banner_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    BannerInfoResp info = GsonImpl.get().toObject(response.toString(), BannerInfoResp.class);
                    bannerList.clear();
                    bannerList.addAll(info.getResult().getData());

                    BannerPagerAdapter bannerPagerAdapter = new BannerAdapter(mActivity, bannerList);
                    banner = (Banner) mActivity.findViewById(R.id.sliding_banner);
                    banner.setDotGravity(Banner.CENTER).
                            setDot(R.drawable.no_selected_dot, R.drawable.selected_dot).
                            setAdapter(bannerPagerAdapter).
                            setOnItemClickListener(new BannerPagerAdapter.onItemClickListener() {
                                @Override
                                public void onClick(int position) {

                                    final BannerInfoResp.ResultEntity.DataEntity bannerInfo = bannerList.get(position);
                                    if (!bannerInfo.getProduct_id().equals("0")) {
                                        Log.e("ssss", "bannerInfo.getProduct_id()==>" + bannerInfo.getProduct_id());
                                        Intent intent = new Intent(mActivity, ProductDetails.class);
                                        intent.putExtra("id", bannerInfo.getProduct_id());
                                        startActivity(intent);
                                    } else if (!bannerInfo.getUrl().equals("")) {
                                        Log.e("ssss", "bannerInfo.getUrl()==>" + bannerInfo.getUrl());
                                        Intent intent = new Intent(mActivity, ActivityWebView.class);
                                        intent.putExtra("url", bannerInfo.getUrl());
                                        startActivity(intent);
                                    }
                                }
                            }).
                            startAutoPlay();

                } else {
                    CustomProgressDialog.Dismiss();

                }
                init();
                GetleftTpye();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    /**
     * Banner适配器
     */
    public class BannerAdapter extends BannerPagerAdapter {
        private Context mContext;
        private List<BannerInfoResp.ResultEntity.DataEntity> data;

        DisplayImageOptions displayImageOptions_tejia = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.loader_tejia)
                .showImageForEmptyUri(R.mipmap.loader_tejia).showImageOnFail(R.mipmap.loader_tejia).cacheInMemory(true).cacheOnDisk(true)
                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();

        public BannerAdapter(Context context, List data) {
            super(context, data);
            mContext = context;
            this.data = data;
        }

        @Override
        public View setView(int position) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.homepager_banner_img, null);
            ImageView iv = (ImageView) v.findViewById(R.id.banner_img);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageLoader.getInstance().displayImage(data.get(position).getThumb(), iv, displayImageOptions_tejia);
            return v;
        }
    }
}